package com.adgox.tiantianbiting.home.index;


import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.TtbtApplication;
import com.adgox.tiantianbiting.adapter.HotAdapter;
import com.adgox.tiantianbiting.adapter.ProgramAdapter;
import com.adgox.tiantianbiting.base.BasicFragment;
import com.adgox.tiantianbiting.bean.MidTabBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.TopBannerBean;
import com.adgox.tiantianbiting.home.category.CategoryActivity;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.home.search.SearchActivity;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.music.MusicService;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.bumptech.glide.Glide;
import com.rae.swift.session.SessionManager;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.xuezj.cardbanner.CardBanner;
import com.xuezj.cardbanner.ImageData;
import com.xuezj.cardbanner.imageloader.CardImageLoader;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeIndexFragment extends BasicFragment implements HomeIndexContract.View, ProgramAdapter.OnItemClickListener, HotAdapter.OnItemClickListener, CardBanner.OnItemClickListener, View.OnClickListener {

    Unbinder unbinder;
    @BindView(R.id.banner)
    CardBanner topBanner;
    @BindView(R.id.mid_banner)
    Banner midBanner;
    @BindView(R.id.rv_program)
    RecyclerView rvProgram;
    @BindView(R.id.rv_hot)
    RecyclerView rvHot;
    @BindView(R.id.icon_tab1)
    ImageView iconTab1;
    @BindView(R.id.tv_tab1)
    TextView tvTab1;
    @BindView(R.id.ll_tab1)
    LinearLayout llTab1;
    @BindView(R.id.icon_tab2)
    ImageView iconTab2;
    @BindView(R.id.tv_tab2)
    TextView tvTab2;
    @BindView(R.id.ll_tab2)
    LinearLayout llTab2;
    @BindView(R.id.icon_tab3)
    ImageView iconTab3;
    @BindView(R.id.tv_tab3)
    TextView tvTab3;
    @BindView(R.id.ll_tab3)
    LinearLayout llTab3;
    @BindView(R.id.icon_tab4)
    ImageView iconTab4;
    @BindView(R.id.tv_tab4)
    TextView tvTab4;
    @BindView(R.id.ll_tab4)
    LinearLayout llTab4;
    @BindView(R.id.icon_tab5)
    ImageView iconTab5;
    @BindView(R.id.tv_tab5)
    TextView tvTab5;
    @BindView(R.id.ll_tab5)
    LinearLayout llTab5;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_play)
    ImageView ivPlay;

    private HomeIndexContract.Presenter mPresenter;
    private PageBean<SubProgramBean> mHotList;
    private List<ProgramBean> mProgramList;
    private List<MidTabBean> mMidTabList;
    private List<TopBannerBean> mTopBannerList;
    private Intent intentService;
    private HomeReceiver receiver;
    private int serviceProgramId;
    private Dialog dialog;
    private Animation animation;

    public static HomeIndexFragment newInstance() {
        return new HomeIndexFragment();
    }


    @Override
    public int getLayoutId(Bundle var1) {
        return R.layout.fragment_home_index;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new HomeIndexPresenterImpl(this);

        DialogUtils.showLoadingDialog(getContext());
        mPresenter.start();
        registerReceiver();
        //旋转动画初始化
        animation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_anim);
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);
    }

    @Override
    public void onResume() {
        super.onResume();
        ifServiceAlive();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity() == null) return;
        ifServiceAlive();
    }

    private void registerReceiver() {
        receiver = new HomeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.adgox.tiantianbiting.music.MusicService2");
        getActivity().registerReceiver(receiver, intentFilter);
    }

    private void ifServiceAlive() {
        ActivityManager am = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : runningServices) {
            if (info.service.getClassName().equals("com.adgox.tiantianbiting.music.MusicService")) {
                intentService = new Intent(getActivity(), MusicService.class);
                intentService.putExtra("option", "home");
                getActivity().startService(intentService);
            }
        }
    }

    @Override
    public void setPresenter(HomeIndexContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        etSearch.setFocusable(false);
        SharedPreferences sp = getActivity().getSharedPreferences("ivplay", Context.MODE_PRIVATE);
        String img = sp.getString("img", null);
        int programId = sp.getInt("programId", -1);
        if (img != null && programId != -1) {
            ivPlay.setVisibility(View.VISIBLE);
            Glide.with(getContext()).load(img).into(ivPlay);
            serviceProgramId = programId;
        }
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onSetTopBanner(List<TopBannerBean> topBannerList) {
        if (topBannerList == null || topBannerList.size() == 0) {
            Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        mTopBannerList = topBannerList;
        ArrayList<ImageData> imageDataList = new ArrayList<>();
        for (TopBannerBean bean : topBannerList) {
            ImageData imageData = new ImageData();
            imageData.setImage(bean.getPic());
            imageDataList.add(imageData);
        }

        topBanner.setDatas(imageDataList).setCardImageLoader(new CardImageLoader() {
            @Override
            public void load(Context context, ImageView imageView, Object path) {
                Glide.with(context).load(path).into(imageView);
            }
        }).setPlay(true).setDelayTime(3000).start();

        topBanner.setOnItemClickListener(this);
    }

    @Override
    public void onGetTopBannerFailed(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetMidTab(List<MidTabBean> midTabList) {
        if (midTabList == null || midTabList.size() == 0) {
            Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        mMidTabList = midTabList;
        ArrayList<ImageView> imageViews = new ArrayList<>();
        imageViews.add(iconTab1);
        imageViews.add(iconTab2);
        imageViews.add(iconTab3);
        imageViews.add(iconTab4);
        imageViews.add(iconTab5);

        ArrayList<TextView> textViews = new ArrayList<>();
        textViews.add(tvTab1);
        textViews.add(tvTab2);
        textViews.add(tvTab3);
        textViews.add(tvTab4);
        textViews.add(tvTab5);

        /**
         * case穿透
         */
        switch (midTabList.size()) {
            case 3:
                llTab4.setVisibility(View.GONE);
            case 4:
                llTab5.setVisibility(View.GONE);
        }

        //设置数据
        for (int i = 0; i < midTabList.size(); i++) {
            Glide.with(getContext()).load(midTabList.get(i).getPic()).centerCrop().into(imageViews.get(i));
            textViews.get(i).setText(midTabList.get(i).getName());
        }

    }

    @Override
    public void onGetMidTabFailed(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetProgram(List<ProgramBean> programList) {
        if (programList == null || programList.size() == 0) {
            Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        mProgramList = programList;
        for (ProgramBean bean : programList) {
            if (bean.getSubProgram() == null || bean.getSubProgram().size() < 3) {
                Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        mProgramList = programList;
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);

        rvProgram.setLayoutManager(manager);
        rvProgram.setHasFixedSize(true);
        rvProgram.setNestedScrollingEnabled(false);
        ProgramAdapter programAdapter = new ProgramAdapter(mProgramList);
        programAdapter.setOnItemClick(this);
        rvProgram.setAdapter(programAdapter);

    }

    @Override
    public void onGetProgramFailed(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetHot(PageBean<SubProgramBean> hotList) {
        if (hotList == null || hotList.getData() == null || hotList.getData().size() == 0) {
            Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        mHotList = hotList;
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);

        rvHot.setLayoutManager(manager);
        rvHot.setNestedScrollingEnabled(false);
        rvHot.setHasFixedSize(true);
        HotAdapter hotAdapter = new HotAdapter(mHotList.getData());
        hotAdapter.setOnItemClick(this);
        rvHot.setAdapter(hotAdapter);
    }

    @Override
    public void onGetHotFailed(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.tv_more_hot)
    public void onMoreHotClicked() {
        toCategory(41, "热听榜单");
    }

    @Override
    public void onProgramItemClick(View view, ProgramAdapter.ViewType viewType, int position) {
        switch (viewType) {
            case MORE:
                toCategory(mProgramList.get(position).getId(), mProgramList.get(position).getTitle());
                break;
            case PROGRAM1:
                toProgram(mProgramList.get(position).getSubProgram().get(0).getId(),
                        mProgramList.get(position).getSubProgram().get(0).getTitle());
                break;
            case PROGRAM2:
                toProgram(mProgramList.get(position).getSubProgram().get(1).getId(),
                        mProgramList.get(position).getSubProgram().get(1).getTitle());
                break;
            case PROGRAM3:
                toProgram(mProgramList.get(position).getSubProgram().get(2).getId(),
                        mProgramList.get(position).getSubProgram().get(2).getTitle());
                break;

        }
    }

    private void toProgram(int programId, String programName) {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
        intent.putExtra("programId", programId);
        intent.putExtra("programName", programName);
        startActivity(intent);
    }

    private void toCategory(int categoryId, String categoryName) {
        Intent intent = new Intent(getActivity(), CategoryActivity.class);
        intent.putExtra("categoryId", categoryId);
        intent.putExtra("categoryName", categoryName);
        startActivity(intent);
    }

    @Override
    public void onHotItemClick(View view, int position) {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            return;
        }
        Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
        intent.putExtra("programId", mHotList.getData().get(position).getId());
        intent.putExtra("programName", mHotList.getData().get(position).getTitle());
        startActivity(intent);
    }

    @OnClick({R.id.ll_tab1, R.id.ll_tab2, R.id.ll_tab3, R.id.ll_tab4, R.id.ll_tab5})
    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_tab1:
                toMidTabCategory(0);
                break;
            case R.id.ll_tab2:
                toMidTabCategory(1);
                break;
            case R.id.ll_tab3:
                toMidTabCategory(2);
                break;
            case R.id.ll_tab4:
                toMidTabCategory(3);
                break;
            case R.id.ll_tab5:
                toMidTabCategory(4);
                break;
        }
    }

    public void toMidTabCategory(int index) {
        if ("xcx".equals(mMidTabList.get(index).getTarget())) {
            dialog = new Dialog(getContext(), R.style.TransparentDialog);
            Window window = dialog.getWindow();
            window.requestFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_towx);
            ImageView iconTowx = dialog.findViewById(R.id.icon_towx);
            ImageView iconCancel = dialog.findViewById(R.id.icon_cancel);
            iconTowx.setOnClickListener(this);
            iconCancel.setOnClickListener(this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        } else {
            //跳栏目
            toCategory(Integer.parseInt(mMidTabList.get(index).getClickUrl()), mMidTabList.get(index).getName());
        }
    }

    @Override
    public void onItem(int position) {
        String target = mTopBannerList.get(position).getTarget();
        String clickUrl = mTopBannerList.get(position).getClickUrl();
        String name = mTopBannerList.get(position).getName();

        if ("program".equals(target)) {
            toProgram(Integer.parseInt(clickUrl), name);
        }
    }

    @OnClick(R.id.et_search)
    public void onSearchClicked() {
        if (SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), SearchActivity.class));
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    @OnClick(R.id.iv_play)
    public void onPlayClicked() {
        toProgram(serviceProgramId, "天天必听");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.icon_towx:
                //跳小程序
                if (!TtbtApplication.wxapi.isWXAppInstalled()) {
                    Toast.makeText(getContext(), "请先安装微信客户端", Toast.LENGTH_SHORT).show();
                    return;
                }
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = "gh_b77d7ffeec87";
                req.path = "/pages/hope/hope?id=49&showhomeicon=fx";
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
                TtbtApplication.wxapi.sendReq(req);
            case R.id.icon_cancel:
                dialog.dismiss();
                break;
        }
    }

    class HomeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String img = bundle.getString("img");
            serviceProgramId = bundle.getInt("programId");
            int status = bundle.getInt("status");
            Glide.with(getContext()).load(img).into(ivPlay);
            ivPlay.setVisibility(View.VISIBLE);
            if (status == 1) {
                ivPlay.clearAnimation();
                //播放状态，开转
                ivPlay.setAnimation(animation);
                ivPlay.startAnimation(animation);
            } else {
                //非播放状态，不转
                ivPlay.clearAnimation();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
